<?php

class stateAction extends sfActions
{
    public function execute($request)
    {
        $job_id = $request->getParameter('job_id');
        $state = $request->getParameter('state');

        $conn = Doctrine_Core::getTable('Job')->getConnection();
        $conn->beginTransaction();
        try {
            // Fetch Job
            $job = $this->getUser()->getPage()->getJobsQuery()
                ->addWhere('j.job_id = ?', $job_id)
                ->fetchOne();

            if (!$job) {
                $conn->rollback();
                $this->getLogger()->debug('{stateAction} Job not found: '.$job_id);
                $this->renderText(json_encode(array(
                            'success' => 0,
                            'is_over_quota' => 0,
                            )));
                return sfView::NONE;
            }


            // Update Job
            if ($request->getParameter('expire'))
                $expires_at = date('Y-m-d h:m:n',strtotime('+2 month'));
            else
                $expires_at = null;

            if ($state === 'active')
                $success = $job->resume($expires_at);
            elseif ($state === 'paused')
                $success = $job->pause();
            elseif ($state === 'inactive')
                $success = $job->stop();

            $conn->commit();
        } catch (Exception $e) {
            $this->getLogger()->debug('{stateAction} Error: '.$e->getMessage());
            $conn->rollback();
            $this->renderText(json_encode(array(
                        'success' => 0,
                        'is_over_quota' => 0,
                        'slots'   => $this->getUser()->getPage()->getActiveJobsCount(),
                        )));
            return sfView::NONE;
        }

        MongoJob::fullSyncFromJob($job);

        $this->renderText(json_encode(array(
                    'success'       => ($success ? 1 : 0),
                    'has_campaign'  => $job->hasCurrentCampaign(),
                    'is_over_quota' => $job->isOverQuota(),
                    'slots'         => $this->getUser()->getPage()->getActiveJobsCount(),
                    )));

        // logging!
        $data = http_build_query(array(
                'job_id'   => $job_id,
                'state'    => $state,
                ), '', '&');
        LogUser::log('backoffice_job_state_change', $job_id, null, $data);

        return sfView::NONE;
    }
}

